#include <iostream>
#include <vector>
#include <memory>
#include <ctime>
#include <random>

/*
 *一定要注意数组中点q被分在数组左侧还是右侧
 *此程序是按照q在左侧,和算法导论一致
 * */

using namespace std;

void merge(vector<int> &vec, int p, int q, int r) //数组，起始坐标，中间坐标，结束坐标
{
	//一下两行易错
	int LEFT_SIZE = q - p + 1;
	int RIGHT_SIZE = r - q;
	vector<int> *lef = new vector<int>; //左边的数组
	vector<int> *rig = new vector<int>; //右边的数组
	shared_ptr<vector<int>> left(lef);
	shared_ptr<vector<int>> right(rig);
	for (int i = 0; i < LEFT_SIZE; i++)
		left->push_back(vec.at(p + i));//此行易错
	for (int i = 0; i < RIGHT_SIZE; i++)
		right->push_back(vec.at(q + i + 1));//此行易错
	left->push_back(9999999);
	right->push_back(9999999);
	int i = 0;
	int j = 0;
	int k;
	for (k = p; k < r + 1; k++)
	{
		if (left->at(i) <= right->at(j))
		{
			vec[k] = left->at(i);
			i++;
		}
		else
		{
			vec[k] = right->at(j);
			j++;
		}
	}
}

void mergeSort(vector<int> &vec, int p, int r) //数组，起始下标，终止下标
{
	// cout << "1" << endl;
	if (p == r)
		return;
	int q = 0;
	q = (p + r) / 2;

	mergeSort(vec, p, q);     //左边的继续分治
	mergeSort(vec, q + 1, r); //右边的继续分治
	merge(vec, p, q, r);  //归并,注意回传的q值,此为q在左侧,例如下标为0-7,此时q=3
}

int main(int argc, char const *argv[])
{
	srand(time(NULL));
	vector<int> vec(8);
	for (int i = 0; i < 8; i++)
		vec[i] = rand() % 100 + 1;
	cout << "排序前：" << endl;
	for (auto ele : vec)
		cout << ele << ",";
	cout << endl;
	mergeSort(vec, 0, vec.size() - 1);
	cout << "排序后：" << endl;
	for (int &ele : vec)
		cout << ele << ",";
	return 0;
}
